package com.itqf.quartz;

import com.alibaba.fastjson.JSON;
import com.itqf.entity.ScheduleJob;
import com.itqf.utils.SpringContextUtils;
import com.itqf.utils.SysConstant;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.lang.reflect.Method;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/10/21
 * @Time: 上午11:49
 */
public class MyJob implements Job {

//    @Resource
//    private TestTask  testTask;  不行，因为MyJob不属于Spring

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        try {
            // System.out.println("helloworld!!");
            //取参数  jobDetail.getJobDataMap().put(SysConstant.DATA_KEY,json);
            String json = (String) jobExecutionContext.getJobDetail().getJobDataMap().get(SysConstant.DATA_KEY);
            //json-->java object
            ScheduleJob schedulerJob = JSON.parseObject(json,ScheduleJob.class);
            //spring容器中bean的名称
            String  beanName = schedulerJob.getBeanName();
            String methodName = schedulerJob.getMethodName();
            System.out.println(beanName+""+methodName);
//        ApplicationContext a = new ClassPathXmlApplicationContext("applicationContext.xml");
//        TestTask testTask = (TestTask) a.getBean("testTask");

            Object object = SpringContextUtils.getBean(beanName);

            Method method = null;

            String  param = schedulerJob.getParams();
            if(param==null){
                method = object.getClass().getMethod(methodName);
                //调方法
                method.invoke(object);
            }else{
                method = object.getClass().getMethod(methodName,String.class);
                //调方法
                method.invoke(object,param);
            }

            //schedule_job_log
//            ScheduleJobLog log = new ScheduleJobLog();
//            log.setJobId(schedulerJob.getJobId());
//            ...
//            scheduleJobLogService = SpringContextUtils.getBean();
//              scheduleJobLogService.saveLog(log);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
